package com.geng.demo.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.geng.demo.domain.pojo.hdata.HLodge;
import com.geng.demo.mybatisplus.hdata.HLodgeMapper;
import com.geng.demo.service.exceldao.ExcelUser;
import com.geng.demo.util.ParamUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.tags.Param;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class HDataService {

    private static final Logger logger = LogManager.getLogger(HDataService.class);

    @Autowired
    HLodgeMapper hLodgeMapper;


    /**
     * 解析excel文件，将智慧园区中的订单ID全量更新到门锁系统中的H_Lodge表的remark字段中
     * 根据姓名、房间号匹配数据，不满足的不做变更
     * @return
     */
    public Map<String, Object> parseExcel(){
        String filename = ".\\file\\user.xlsx";

        //查询门锁系统全部入住中的数据
        List<HLodge> hLodges = hLodgeMapper.selectInWithNoRemark();

        // 读取excel
        EasyExcel.read(filename, ExcelUser.class, new AnalysisEventListener<ExcelUser>() {
            // 每解析一行数据,该方法会被调用一次
            @Override
            public void invoke(ExcelUser excelUser, AnalysisContext analysisContext) {
                logger.info("解析数据为:" + JSONUtil.toJsonStr(excelUser));
                String ddid = excelUser.getDdid();
                String name = excelUser.getName();
                String roomNumber = excelUser.getRoomNumber();
                Optional<HLodge> first = hLodges.stream().filter(x -> {
                    String roomname = x.getRoomname();  //房间号
                    String guest = x.getGuest();    //姓名
                    return ObjectUtil.equal(roomNumber, roomname) && ObjectUtil.equal(name, guest);
                }).findFirst();
                if(first.isPresent()){
                    HLodge hLodge = first.get();
                    hLodge.setRemark(ddid);
                    hLodgeMapper.updateById(hLodge);
                }
            }
            // 全部解析完成被调用
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                logger.info("解析完成...");
                // 可以将解析的数据保存到数据库
            }
        }).sheet().doRead();

        return ParamUtil.returnSuccessMap();
    }
}
